package se.teamstat.server.dto;

import java.util.List;

import javax.jdo.PersistenceManager;

import se.teamstat.server.service.PMF;

public abstract class DAO<E> {
	
	private static final long serialVersionUID = -7873170466207570008L;
	
	public E save(E entity) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			entity = pm.makePersistent(entity);
			return entity;
		} finally {
			pm.close();
		}
	}

	public void update(E newEntity) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Object id = pm.getObjectId(newEntity);
			E oldEntity = pm.getObjectById(getType(), id);
			copy(oldEntity, newEntity);
		} catch(Exception e) {
			System.out.println("Kalle:" + e);
		} finally {
			pm.close();
		}
	}
	
	public abstract void copy(E oldEntity, E newEntity);
	public abstract Class<E> getType();
	
	public List<E> getAll() {
		String query = "select from " + getClassName();    
		List<E> entities = (List<E>) getPersistenceManager().newQuery(query).execute();
		return entities;
	}
	
	public String getClassName() {
		return getType().getName();
	}
	
	public PersistenceManager getPersistenceManager() {
		return PMF.get().getPersistenceManager();
	}

}
